import React, { useState } from 'react';
import { TextField, Button, Select, MenuItem, FormControl, InputLabel, Box, SelectChangeEvent, Typography } from '@mui/material';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider, DatePicker } from '@mui/x-date-pickers';
import { addDays, format } from 'date-fns';

interface Product {
  id: string;
  name: string;
}

interface InvestmentFormProps {
  products: Product[];
  initialData?: {
    investmentId: string;
    productId: string;
    principal: number;
    startDate: Date;
    endDate: Date;
  } | null;
  onSubmit: (data: InvestmentFormData) => void;
  onClose: () => void;
}

interface InvestmentFormData {
  productId: string;
  principal: number;
  startDate: Date;
  endDate: Date;
  id?: string;  // 添加可选的ID字段用于编辑现有投资计划
}

const durationOptions = [
  { value: 1, label: '1天' },
  { value: 7, label: '7天' },
  { value: 14, label: '14天' },
  { value: 30, label: '30天' },
  { value: 60, label: '60天' },
  { value: 180, label: '180天' },
  { value: 360, label: '360天' },
];

const InvestmentForm: React.FC<InvestmentFormProps> = ({ products, initialData, onSubmit, onClose }) => {
  const [productId, setProductId] = useState(initialData?.productId || '');
  const [principal, setPrincipal] = useState(initialData?.principal.toString() || '');
  const [startDate, setStartDate] = useState<Date | null>(initialData?.startDate || new Date());
  const [endDate, setEndDate] = useState<Date | null>(initialData?.endDate || null);

  const handleProductChange = (event: SelectChangeEvent<string>) => {
    setProductId(event.target.value);
  };

  const handlePrincipalChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setPrincipal(event.target.value);
  };

  const handleStartDateChange = (date: Date | null) => {
    try {
      setStartDate(date);
      if (date && endDate && date > endDate) {
        setEndDate(null);
      }
    } catch (error) {
      console.error('处理开始日期变更失败:', error);
    }
  };

  const handleEndDateChange = (date: Date | null) => {
    try {
      setEndDate(date);
    } catch (error) {
      console.error('处理结束日期变更失败:', error);
    }
  };

  const handleDurationChange = (event: SelectChangeEvent<number>) => {
    try {
      if (startDate) {
        const duration = Number(event.target.value);
        if (!isNaN(duration)) {
          setEndDate(addDays(startDate, duration));
        }
      }
    } catch (error) {
      console.error('处理期限选择失败:', error);
    }
  };

  const [error, setError] = useState<string | null>(null);

  const validateForm = () => {
    if (!productId) {
      setError('请选择理财产品');
      return false;
    }
    if (!principal || parseFloat(principal) <= 0) {
      setError('请输入有效的投资本金');
      return false;
    }
    if (!startDate) {
      setError('请选择购买时间');
      return false;
    }
    if (!endDate) {
      setError('请选择结束时间');
      return false;
    }
    if (startDate > endDate) {
      setError('结束时间不能早于购买时间');
      return false;
    }
    setError(null);
    return true;
  };

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    if (validateForm() && startDate && endDate) {
      const formData: InvestmentFormData = {
        productId,
        principal: parseFloat(principal),
        startDate,
        endDate,
      };
      
      // 如果是编辑模式，添加ID
      if (initialData?.investmentId) {
        formData.id = initialData.investmentId;
      }
      
      onSubmit(formData);
    }
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <form onSubmit={handleSubmit}>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, margin: '20px' }}>
          <FormControl fullWidth>
            <InputLabel id="product-select-label">选择理财产品</InputLabel>
            <Select
              labelId="product-select-label"
              value={productId}
              onChange={handleProductChange}
              label="选择理财产品"
            >
              {products.map((prod) => (
                <MenuItem key={prod.id} value={prod.id}>{prod.name}</MenuItem>
              ))}
            </Select>
          </FormControl>

          <TextField
            label="投资本金"
            type="number"
            value={principal}
            onChange={handlePrincipalChange}
            fullWidth
          />

          <DatePicker
            label="购买时间"
            value={startDate}
            onChange={handleStartDateChange}
            renderInput={(params) => <TextField {...params} fullWidth />}
            inputFormat="yyyy-MM-dd"
          />

          <DatePicker
            label="结束时间"
            value={endDate}
            onChange={handleEndDateChange}
            renderInput={(params) => <TextField {...params} fullWidth />}
            minDate={startDate || undefined}
            inputFormat="yyyy-MM-dd"
          />

          <FormControl fullWidth>
            <InputLabel id="duration-select-label">快速选择期限</InputLabel>
            <Select
              labelId="duration-select-label"
              onChange={handleDurationChange}
              label="快速选择期限"
            >
              {durationOptions.map((option) => (
                <MenuItem key={option.value} value={option.value}>{option.label}</MenuItem>
              ))}
            </Select>
          </FormControl>

          {error && (
            <Typography color="error" variant="body2" sx={{ mt: 1 }}>
              {error}
            </Typography>
          )}
          <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2, mt: 2 }}>
            <Button onClick={onClose} variant="outlined">
              取消
            </Button>
            <Button type="submit" variant="contained" color="primary">
              {initialData ? '保存修改' : '添加投资计划'}
            </Button>
          </Box>
        </Box>
      </form>
    </LocalizationProvider>
  );
};

export default InvestmentForm;